<template>
  <!-- 菌落形态类型 -->
  <div id="colonialMorphologyType">
    <Breadcrumb content="菌落形态类型" />
    <div class="bodyContent">
      <vxe-toolbar perfect>
        <template #buttons>
          <vxe-input type='search' v-model='form.searchValue' clearable class='vxeInputSearch'
            @search-click='handleSearch' @clear='handleSearch' @keyup.enter.native='handleSearch'
            placeholder='关键字查询'></vxe-input>

          <vxe-button type='text' class='button-blue' @click='findColonialMorphologyTypeOptList'
            icon='vxe-icon-refresh'>刷新
          </vxe-button>
          <vxe-button type='text' class='button-blue' @click='handleAdd' icon='vxe-icon-square-plus'>新增</vxe-button>
          <vxe-button type='text' class='button-blue' @click='saveList' icon='vxe-icon-save'>保存</vxe-button>
          <vxe-button type='text' class='button-red' @click='handleDelete' icon='vxe-icon-delete'>删除</vxe-button>
        </template>
      </vxe-toolbar>
      <div class="colonialMorphologyTypeOptTable">
        <vxe-table ref="colonialMorphologyTypeOptTable" v-loading="loading" class="mytable-scrollbar" border height="auto"
          :data="colonialMorphologyTypeOptList" @cell-click="colonialMorphologyTypeOptRowClick"
          :row-config="{ isCurrent: true, isHover: true }" :mouse-config="{ selected: true }"
          :edit-config="{ trigger: 'click', mode: 'cell', showIcon: false }" resizable show-overflow>
          <vxe-column type="checkbox" width="26"></vxe-column>
          <vxe-column type="seq" title="序号" width="30"></vxe-column>
          <vxe-column field="code" title="编码" width="60" :edit-render="{ autofocus: '.vxe-input--inner' }">
            <template #edit="{ row, rowIndex, column }">
              <vxe-input v-model="row.code" type="text"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="name" title="可选项" width="120" :edit-render="{ autofocus: '.vxe-input--inner' }">
            <template #edit="{ row, rowIndex, column }">
              <vxe-input v-model="row.name" type="text"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="inputCode" title="输入码" width="80" :edit-render="{ autofocus: '.vxe-input--inner' }">
            <template #edit="{ row, rowIndex, column }">
              <vxe-input v-model="row.inputCode" type="text"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="description" title="描述" width="160" :edit-render="{ autofocus: '.vxe-input--inner' }">
            <template #edit="{ row, rowIndex, column }">
              <vxe-input v-model="row.description" type="text"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="imageUrl" title="示意图地址" width="200" :edit-render="{ autofocus: '.vxe-input--inner' }">
            <template #edit="{ row, rowIndex, column }">
              <el-upload class="upload-demo" :data="paramData" :headers="headers" :action="uploadFilePath"
                :show-file-list="false" multiple :on-success="onSuccess" :on-error="onError">
                <vxe-input v-model="row.imageUrl" type="text">
                </vxe-input>
              </el-upload>
            </template>
          </vxe-column>
          <vxe-column field="morphologyType" title="形态类型" align="left" width="150"
            :edit-render="{ autofocus: '.vxe-input--inner' }">
            <template #default="{ row }">
              {{ dataType(row.morphologyType) }}
            </template>
            <template #edit="{ row }">
              <vxe-select v-model="row.morphologyType" placeholder="" clearable transfer
                class-name="width-100-percentage">
                <vxe-option v-for="(item, index) in morphologyTypes" :key="index" :label="item.name"
                  :value="item.code"></vxe-option>
              </vxe-select>
            </template>
          </vxe-column>
          <vxe-column field="isStatic" title="是否静态" width="60" align="center">
            <template #default="{ row }">
              <strong :class="row.isStatic === 1 ? 'text-green' : 'text-red'">{{
                row.isStatic === 1 ? '是' : '否'
              }}</strong>
            </template>
          </vxe-column>
          <vxe-column field="seq" title="显示顺序" min-width="60" :edit-render="{ autofocus: '.vxe-input--inner' }">
            <template #edit="{ row, rowIndex, column }">
              <vxe-input v-model="row.seq" type="text"></vxe-input>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </div>
  </div>
</template>
<script setup lang='ts'>
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import { VxeMessage, VxeNotifyType } from "@/utils/CommonMessage";
import Breadcrumb from '@/components/Breadcrumb.vue';
import { IsEmpty } from '@/utils/common';

let { proxy }: any = getCurrentInstance();

let loading = ref(false); //查询按钮加载
let currentRowIndex = 0;
let form = reactive({
  searchValue: '',
});
let headers = {
  Authorization: 'Bearer ' + localStorage.getItem('token')
};
let colonialMorphologyTypeOptList = reactive([]);//列表
let currentColonialMorphologyTypeOpt = reactive({});
// 形态类型 morphologyTypes
let morphologyTypes: any = reactive([]); //字典表：菌落形态类型
// 上传图片
const uploadFilePath = ref((window as any).apiUrl.VITE_SERVER_URL + '/bac/germ/morphologyType/uploadImage',);
// 请求参数数据
const paramData = reactive({
  morphologyId: '',
  id: ''
});
// 方法定义区 =============

// 页面加载时
onMounted(() => {
  getDictDetailList();
  findColonialMorphologyTypeOptList();

});

function dataType(morphologyType) {
  if (!IsEmpty(morphologyTypes)) {
    const item = morphologyTypes.find((item) => item.code === morphologyType);
    return item ? item.name : '';
  }
}

// 上传成功
function onSuccess(e) {
  if (e && e.status && e.status.code && e.status.code === 400) {
    VxeMessage(e.status.msg.replace('IOException: ', ''), VxeNotifyType.error);
    return;
  }
  currentColonialMorphologyTypeOpt.imageUrl = e.data
  save();
}

//上传失败
function onError(e) {
  console.log('失败', e);
}

//从词典获取菌落形态
function getDictDetailList() {
  morphologyTypes.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'gremMorphologyType' } })
    .then((res: any) => {
      morphologyTypes.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

//获取列表
function findColonialMorphologyTypeOptList() {
  colonialMorphologyTypeOptList.length = 0;
  loading.value = true;
  const url = '/sta/germ/morphologyType/findPageList';
  const data = {
    searchValue: IsEmpty(form.searchValue) ? '' : form.searchValue.trim(),
    sorting: ''
  };
  proxy.$http.get(url, { params: data })
    .then((res: any) => {
      colonialMorphologyTypeOptList.push(...res.data);
      loading.value = false;
    }).catch((err) => {
      loading.value = false;
      VxeMessage('获取列表', VxeNotifyType.error);
    });
}

//查询
function handleSearch() {
  findColonialMorphologyTypeOptList();
}

//新增性状
function handleAdd() {
  const newRow = {
    id: null,
    code: '',
    name: '',
    morphologyType: '',
    isStatic: 0,
    inputCode: '',//输入码
    description: '',//描述
    diagrammaticSketchPath: ''//示意图地址
  };
  colonialMorphologyTypeOptList.unshift(newRow);
  const $table = (proxy.$refs.colonialMorphologyTypeOptTable as any);
  $table.reloadData(colonialMorphologyTypeOptList);
  $table.setEditRow(newRow);
  $table.setCurrentRow(newRow);
}

// 行点击事件
function colonialMorphologyTypeOptRowClick({ row, rowIndex }) {
  if (IsEmpty(row)) {
    currentColonialMorphologyTypeOpt = {} as any;
    return;
  }
  currentRowIndex = rowIndex;
  currentColonialMorphologyTypeOpt = row;
  (proxy.$refs.colonialMorphologyTypeOptTable as any).setCurrentRow(row)
}

//单个保存
function save() {
  loading.value = true;
  const url = '/sta/germ/morphologyType/saveOrUpdate';
  proxy.$http
    .post(url, currentColonialMorphologyTypeOpt)
    .then((res: any) => {
      VxeMessage('保存成功', VxeNotifyType.success);
      findColonialMorphologyTypeOptList();
    })
    .catch((err) => {
      VxeMessage('保存失败', VxeNotifyType.error);
    });
}
//批量保存
function saveList() {
  loading.value = true;
  const url = '/sta/germ/morphologyType/saveOrUpdateBatch';
  proxy.$http
    .post(url, colonialMorphologyTypeOptList)
    .then((res: any) => {
      VxeMessage('保存成功', VxeNotifyType.success);
      findColonialMorphologyTypeOptList();
    })
    .catch((err) => {
      VxeMessage('保存失败', VxeNotifyType.error);
    });
}

//删除
function handleDelete() {
  const $xTable = proxy.$refs.colonialMorphologyTypeOptTable as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请先选中要删除的项', VxeNotifyType.info);
    return;
  }
  proxy.$XModal.confirm('您确定要删除吗？').then(type => {
    if (type === 'confirm') {
      const url = '/sta/germ/morphologyType/deleteBatch';
      proxy.$http
        .post(url, selectRows)
        .then((res: any) => {
          findColonialMorphologyTypeOptList();
        })
        .catch((err) => {
          VxeMessage('删除成功', VxeNotifyType.error);
        });
    }
  });
}


</script>
<style lang='scss' scoped>
#colonialMorphologyType {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .colonialMorphologyTypeOptTable {
      background-color: $base-white;
      height: calc(100% - 40px);
    }
  }

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

}
</style>